package com.jeecg.demo.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jeecg.demo.entity.ShopsEntity;
import com.jeecg.demo.entity.SysOrderVerifyEntity;
import com.jeecg.demo.entity.TraderEntity;
import com.jeecg.demo.service.ShopsServiceI;
import com.jeecg.demo.service.SysOrderVerifyServiceI;
import com.jeecg.demo.util.GetUserTenantId;
import com.jeecg.demo.util.PopupDataBindUtil;

/**
 * @Title: Controller
 * @Description: SHOPS
 * @author onlineGenerator
 * @date 2018-11-19 09:39:31
 * @version V1.0
 * 
 */
@Controller
@RequestMapping("/shopsController")
public class ShopsController extends BaseController {
    private static final Logger logger = LoggerFactory
            .getLogger(ShopsController.class);

    @Autowired
    private ShopsServiceI shopsService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private PopupDataBindUtil bindUtil;
    @Autowired
    private SysOrderVerifyServiceI sysOrderVerifyService;

    /**
     * SHOPS列表 页面跳转
     * 
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request, String type) {
        request.setAttribute("type", type);
        return new ModelAndView("com/jeecg/demo/shopsList");
    }

    /**
     * easyui AJAX请求数据
     * 
     * @param request
     * @param response
     * @param dataGrid
     * @param user
     * @throws Exception
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(ShopsEntity shops, HttpServletRequest request,
            HttpServletResponse response, DataGrid dataGrid, String type)
            throws Exception {
        CriteriaQuery cq = new CriteriaQuery(ShopsEntity.class, dataGrid);
        String fullname = request.getParameter("fullname");
        // 查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                shops, request.getParameterMap());
        try {
        	if ("sh".equals(type)) {
        		cq.eq("shopstate", "1");
        		cq.add();
        	}
        	if (StringUtils.isNotEmpty(fullname)) {
        		List<TraderEntity> list = systemService.findByProperty(TraderEntity.class, "fullname", fullname);
        		if (list.size()>0) {
        			String[] traderidArr = new String[list.size()];
        			for (int j = 0; j < list.size(); j++) {
        				String traderid = String.valueOf(list.get(j).getTraderid());
        				traderidArr[j]=traderid;
        			}
        			cq.in("traderid", traderidArr);
        			cq.add();
        		}else{
        			cq.eq("traderid", "-1");
        			cq.add();
        		}
        	}
        }
        catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.shopsService.getDataGridReturn(cq, true);

        // 绑定非字典表数据
        bindUtil.BindDDName(dataGrid, "trader", "fullname", "traderid",
                "traderid", "fullname");

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 删除SHOPS
     * 
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(ShopsEntity shops, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        shops = systemService.getEntity(ShopsEntity.class, shops.getId());
        message = "删除成功";
        try {
            shopsService.delete(shops);
            systemService.addLog(message, Globals.Log_Type_DEL,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除SHOPS
     * 
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "删除成功";
        try {
            for (String id : ids.split(",")) {
                ShopsEntity shops = systemService.getEntity(ShopsEntity.class,
                        Integer.parseInt(id));
                shopsService.delete(shops);
                systemService.addLog(message, Globals.Log_Type_DEL,
                        Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 添加SHOPS
     * 
     * @param ids
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(ShopsEntity shops, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "添加成功";
        GetUserTenantId getuserfun = new GetUserTenantId();
        String idString = String
                .valueOf(systemService.findOneForJdbc(getuserfun.getSql(),
                        getuserfun.getOrgcode()).get("worktypeid"));
        int worktypeid = Integer.parseInt(idString);
        shops.setWorktypeid(worktypeid);
        shops.setBusinesstype("3");
        try {
            shopsService.save(shops);
            systemService.addLog(message, Globals.Log_Type_INSERT,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 更新SHOPS
     * 
     * @param ids
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(ShopsEntity shops, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "更新成功";
        ShopsEntity t = shopsService.get(ShopsEntity.class, shops.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(shops, t);
            shopsService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * SHOPS新增页面跳转
     * 
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(ShopsEntity shops, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(shops.getId())) {
            shops = shopsService.getEntity(ShopsEntity.class, shops.getId());
            req.setAttribute("shopsPage", shops);
        }
        return new ModelAndView("com/jeecg/demo/shops-add");
    }

    /**
     * SHOPS编辑页面跳转
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(ShopsEntity shops, HttpServletRequest req)
            throws Exception {
        if (StringUtil.isNotEmpty(shops.getId())) {
            shops = shopsService.getEntity(ShopsEntity.class, shops.getId());
            Object obj = shops;
            // 绑定非字典表数据
            Map<String, Object> resultList = bindUtil.BindDDName(obj, "trader",
                    "fullname", "traderid", "traderid", "fullname");
            Map<String, Object> resultList1 = bindUtil.BindDDName(obj,
                    "SHOPIMGS", "imgname", "shopid", "shopid", "imgname");
            Map<String, Object> resultList2 = bindUtil.BindDDName(obj,
                    "SHOPIMGS", "imgurl", "shopid", "shopid", "imgname");
            req.setAttribute("shopsPage", resultList);
            req.setAttribute("shopsPage1", resultList1);
            req.setAttribute("shopsPage2", resultList2);
            req.setAttribute("lbimg", resultList2.get("imgname").toString()
                    .replace(" ", ""));
            req.setAttribute("action", "shopsController.do?doUpdate");
        }
        return new ModelAndView("com/jeecg/demo/shops-update");
    }

    /**
     * SHOP审核页面跳转
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(params = "goVerify")
    public ModelAndView goVerify(ShopsEntity shops, HttpServletRequest req)
            throws Exception {
        if (StringUtil.isNotEmpty(shops.getId())) {
            shops = shopsService.getEntity(ShopsEntity.class, shops.getId());
            Object obj = shops;
            // 绑定非字典表数据
            Map<String, Object> resultList = bindUtil.BindDDName(obj, "trader",
                    "fullname", "traderid", "traderid", "fullname");
            Map<String, Object> resultList1 = bindUtil.BindDDName(obj,
                    "SHOPIMGS", "imgname", "shopid", "shopid", "imgname");
            Map<String, Object> resultList2 = bindUtil.BindDDName(obj,
                    "SHOPIMGS", "imgurl", "shopid", "shopid", "imgname");
            System.out.println(resultList2.get("imgname").toString().replace(
                    " ", ""));
            req.setAttribute("shopsPage", resultList);
            req.setAttribute("shopsPage1", resultList1);
            req.setAttribute("shopsPage2", resultList2);
            req.setAttribute("shopsPageEntity", shops);
            req.setAttribute("lbimg", resultList2.get("imgname").toString()
                    .replace(" ", ""));
            req.setAttribute("action", "shopsController.do?doVerify");
        }
        return new ModelAndView("com/jeecg/demo/shops-update");
    }

    /**
     * 审核SHOP
     * 
     * @param ids
     * @return
     */
    @RequestMapping(params = "doVerify")
    @ResponseBody
    public AjaxJson doVerify(ShopsEntity shops, HttpServletRequest request,
            String verifyflag, String verifynote) {
        String message = null;
        AjaxJson j = new AjaxJson();

        ShopsEntity t = shopsService.get(ShopsEntity.class, shops.getId());
        TSUser u = ResourceUtil.getSessionUser();
        String beforestatus = "";
        try {
            // 根据认证申请状态判断审核前状态
            if (t.getShopstate().equals("1") || t.getShopstate().equals("2")) {
                beforestatus = "1";
            }
            else if (t.getShopstate().equals("3")) {
                beforestatus = "2";
            }
            else if (t.getShopstate().equals("4")) {
                beforestatus = "3";
            }

            // 设置审核记录
            SysOrderVerifyEntity verify = new SysOrderVerifyEntity();
            verify.setOrdid(shops.getId());
            verify.setOrdtype("SHOPVERIFY");
            verify.setBeforestatus(beforestatus);
            verify.setVerifyuserid(0);
            verify.setVerifynote(verifynote);
            verify.setVerifytime(new Date());
            verify.setOrderid(1);

            if ("true".equals(verifyflag)) {
                message = "审核成功";

                if (null != verifynote && !verifynote.equals("")) {
                    message += "\r\n审核意见:" + verifynote;
                }

                // 保存审核记录
                verify.setVerifystatus("2");
                sysOrderVerifyService.save(verify);

                // 保存状态
                t.setShopstate("2");
                shopsService.saveOrUpdate(t);

                systemService.addLog(message, Globals.Log_Type_OTHER,
                        Globals.Log_Leavel_INFO);
            }
            else if ("false".equals(verifyflag)) {
                message = "审核退回";

                if (null != verifynote && !verifynote.equals("")) {
                    message += "\r\n退回原因:" + verifynote;
                }

                // 保存审核记录
                verify.setVerifystatus("3");
                sysOrderVerifyService.save(verify);

                // 保存状态
                t.setShopstate("3");
                shopsService.saveOrUpdate(t);

                systemService.addLog(message, Globals.Log_Type_OTHER,
                        Globals.Log_Leavel_INFO);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
            message = "审核失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     * 
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        req.setAttribute("controller_name", "shopsController");
        return new ModelAndView("common/upload/pub_excel_upload");
    }

    /**
     * 导出excel
     * 
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(ShopsEntity shops, HttpServletRequest request,
            HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(ShopsEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                shops, request.getParameterMap());
        List<ShopsEntity> shopss = this.shopsService.getListByCriteriaQuery(cq,
                false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "SHOPS");
        modelMap.put(NormalExcelConstants.CLASS, ShopsEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("SHOPS列表",
                "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, shopss);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出审核信息
     */

    /*
     * @RequestMapping(params = "exportXlsSH") public String
     * exportXlsSH(ShopsEntity shops, HttpServletRequest request,
     * HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
     * System.out.println("111"); CriteriaQuery cq = new
     * CriteriaQuery(ShopsEntity.class, dataGrid); cq.eq("shopstate", "1");
     * cq.add();
     * org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
     * shops, request.getParameterMap()); List<ShopsEntity> shopss =
     * this.shopsService.getListByCriteriaQuery(cq, false);
     * modelMap.put(NormalExcelConstants.FILE_NAME, "SHOPS");
     * modelMap.put(NormalExcelConstants.CLASS, ShopsEntity.class);
     * modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("SHOPS列表",
     * "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
     * modelMap.put(NormalExcelConstants.DATA_LIST, shopss); return
     * NormalExcelConstants.JEECG_EXCEL_VIEW; }
     */

    /**
     * 导出excel 使模板
     * 
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(ShopsEntity shops, HttpServletRequest request,
            HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "SHOPS");
        modelMap.put(NormalExcelConstants.CLASS, ShopsEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("SHOPS列表",
                "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /*
     * @SuppressWarnings("unchecked")
     * 
     * @RequestMapping(params = "importExcel", method = RequestMethod.POST)
     * 
     * @ResponseBody public AjaxJson importExcel(HttpServletRequest request,
     * HttpServletResponse response) { AjaxJson j = new AjaxJson();
     * 
     * MultipartHttpServletRequest multipartRequest =
     * (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap
     * = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile>
     * entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();//
     * 获取上传文件对象 ImportParams params = new ImportParams();
     * params.setTitleRows(2); params.setHeadRows(1); params.setNeedSave(true);
     * try { List<ShopsEntity> listShopsEntitys = ExcelImportUtil
     * .importExcel(file.getInputStream(), ShopsEntity.class, params); for
     * (ShopsEntity shops : listShopsEntitys) { shopsService.save(shops); }
     * j.setMsg("文件导入成功！"); } catch (Exception e) { j.setMsg("文件导入失败！");
     * logger.error(e.getMessage()); } finally { try {
     * file.getInputStream().close(); } catch (IOException e) {
     * e.printStackTrace(); } } } return j; }
     */

}
